﻿/*
   Copyright 2014 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using Flower.Services;
using Flower.Services.Data;
using Jurassic;
using Jurassic.Library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Flower.Directory.Util;
using Flower.Directory.Scripting.Functions.Waiting;

namespace Flower.Directory.Scripting.Functions.Locking
{
    internal class Unlock : ClrFunction
    {
        public Unlock(ScriptEngine engine)
            : base(engine.Function.InstancePrototype, "__unlock", engine.Function.InstancePrototype)
        {
        }

        [JSCallFunction]
        public void Exec(ArrayInstance resources, string owner)
        {
            try
            {
                IDirectory dir = Engine.GetDirectory();

                Exec(dir, resources.ElementValues.Select(el => el.ToString()).ToArray(), owner);
            }
            catch (JavaScriptException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new JavaScriptException(Engine, "Error", ex.Message, ex);
            }
        }

        [ClrScript]
        public static void Exec(IDirectory dir, IList<string> resources, string owner)
        {
            foreach (string res in resources)
            {
                Util.DemandLock.Acquire(res);

                var lockMessage = dir.Get(string.Concat(res, "/", owner)) as Message;

                if (lockMessage != null)
                {
                    int lockCount = lockMessage.Data.To<int>() - 1;

                    if (lockCount == 0)
                    {
                        dir.Remove(lockMessage.Id);
                    }
                    else
                    {
                        lockMessage.Data = lockCount.ToBlob(lockMessage.Data.Format);
                        dir.Save(null, lockMessage);
                    }

                    ReleaseWaiters.Exec(dir, res, WaitingFolders.PutWaiters, 1);
                }
            }
        }
    }
}
